<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use Mine\MineModel;

/**
 * @property int $id 主键
 * @property int $main_uid 主账号id
 * @property int $uid 私域用户ID
 * @property int $robot_id 机器人id
 * @property int $sop_id sop_id
 * @property int $template_id 模板id
 * @property int $status 0=等待中 1=发送中 2=成功 3=失败 4=暂停 5=取消
 * @property int $template_type 1标准模板  2标签sop模板 3新客户模板  4.群模板
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property int $custom_total 客户总量
 * @property int $success_total 成功总量
 * @property int $fail_total 失败总量
 * @property string $crowd_total 群数量
 */
class ChSopSubTask extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_sop_sub_task';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'main_uid', 'uid', 'robot_id', 'sop_id', 'template_id', 'status', 'template_type', 'created_at', 'updated_at', 'custom_total', 'success_total', 'fail_total', 'crowd_total'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'main_uid' => 'integer', 'uid' => 'integer', 'robot_id' => 'integer', 'sop_id' => 'integer', 'template_id' => 'integer', 'status' => 'integer', 'template_type' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'custom_total' => 'integer', 'success_total' => 'integer', 'fail_total' => 'integer'];

    public static function saveSubTask($sop,$robot_id,$custom_total,$crowd_total,$success_total)
    {
        $model=self::query()->firstOrCreate([
            'sop_id'=>$sop['id'],
            'robot_id'=>$robot_id
        ],[
            'main_uid'=>$sop['main_uid'],
            'uid'=>$sop['uid'],
            'template_type'=>$sop['template_type'],
        ]);
        if($custom_total){
            $model->increment('custom_total',$custom_total);
        }
        if($crowd_total){
            $model->increment('crowd_total',$crowd_total);
        }
        if($success_total){
            $model->increment('success_total',$success_total);
        }
        return $model;
    }

    public function robot()
    {
        return $this -> hasOne(ChRobot::class,'id','robot_id');
    }

    public function template()
    {
        return $this -> hasOne(ChSopTemplate::class,'id','template_id');
    }

}
